package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Category;
import com.itheima.bean.PageParam;
import com.itheima.bean.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService cs;

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category){
        //1、调用service
        int row = cs.add(category);
        if (row > 0){
            return R.success("添加分类成功");
        } else {
            return R.error("添加分类失败");
        }
    }

    /**
     * 分页查询分类
     * @param param
     * @return
     */
    @GetMapping("/{param}")
    public R findPage(@PathVariable String param){
        //1、把接收到的json字符串转化成JavaBean对象
        PageParam pageParam = JSON.parseObject(param, PageParam.class);
        //2、调用service
        IPage<Category> page = cs.findPage(pageParam);

        //3、拼接数据返回
        try {
            return R.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("分页查询失败");
        }
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable long id){
        //1、调用service
        int row = cs.delete(id);
        if (row > 0){
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        //1、调用service
        int row = cs.update(category);
        if (row > 0){
            return R.success("修改分类成功");
        } else {
            return R.error("修改分类失败");
        }
    }

    /**
     * 根据type来查找分类数据
     * @param type 1：即表示要查询菜品分类，2：想要查询套餐的分类
     * @return
     */
    @GetMapping("/type/{type}")
    public R findByType(@PathVariable int type){
        try {
            //1、调用service
            List<Category> list = cs.findByType(type);
            //返回
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询分类数据失败");
        }
    }


    //查询所有的分类
    @GetMapping("/list")
    public R findAll(){
        List<Category> list = cs.findAll();
        return R.success(list);
    }
}
